/**
 * $Revision: 1.0 $
 * $Author: Eric Yang $
 * $Date: Aug 7, 2009 10:45:01 PM $
 *
 * Author: Eric Yang
 * Date  : Aug 7, 2009 10:45:01 PM
 *
 */
package com.gooex.service.organization.impl;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.c4j.string.StringTools;
import org.c4j.system.web.hibernate.BaseHibernateService;

import com.gooex.domain.organization.Role;
import com.gooex.service.organization.AuthorityContext;
import com.gooex.service.organization.IRoleManager;
import com.gooex.service.organization.exception.RoleException;

/**
 * @author Eric Yang
 * @version 1.0
 */
public class RoleManagerImpl extends BaseHibernateService implements IRoleManager {

	private static final Log logger = LogFactory.getLog(RoleManagerImpl.class);
	
	public Role getRole(String id) {
		if (StringTools.isBlankOrNull(id))
			return null;
		return (Role) getHibernateTemplate().get(Role.class, id);
	}

	public List<Role> getRoles() {
		return getHibernateTemplate().find("from Role");
	}

	public Role getRoleByName(String name) {
		String hql = "from " + Role.class.getName() + " where name=?";
		List<Role> roles = getHibernateTemplate().find(hql, name);
		if (roles != null && roles.size() == 1)
			return roles.get(0);
		return null;
	}

	public void saveRole(Role role) {
		if (StringTools.isBlankOrNull(role.getId())) {
			role.setId(null);
		}
		getHibernateTemplate().saveOrUpdate(role);
	}

	public void removeRole(Role role) throws RoleException {
		role = getRole(role.getId());
		if (AuthorityContext.getSuperRole().equals(role)) {
			logger.debug("Role[" + role.getName() + "] is super role, can't be removed!");
			throw new RoleException("Can't remove super role!");
		}
		getHibernateTemplate().delete(role);
	}

}
